import * as Cesium from "cesium";
import { ref } from 'vue'
const Token = import.meta.env.VITE_ACROSS_TOKEN; // 获取token
import { cities } from './db_city'
import { countries } from './db_country'
export const dialogVisible = ref(false); // 弹窗控制
export const dialogContent = ref({})

// 图层管理函数
export function updateMapLayer(viewer, layerType) {
    // 移除所有现有图层
    viewer.imageryLayers.removeAll();

    let baseLayer, labelLayer;

    switch (layerType) {
        case 'vector':
            // 矢量地图
            baseLayer = new Cesium.UrlTemplateImageryProvider({
                url: 'https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                maximumLevel: 18,
                credit: '高德地图'
            });
            viewer.imageryLayers.addImageryProvider(baseLayer);
            break;

        case 'satellite':
            // 卫星影像
            baseLayer = new Cesium.UrlTemplateImageryProvider({
                url: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                maximumLevel: 18,
                credit: '高德地图影像'
            });
            viewer.imageryLayers.addImageryProvider(baseLayer);
            break;

        case 'vectorWithLabels':
            // 矢量地图 + 标注
            baseLayer = new Cesium.UrlTemplateImageryProvider({
                url: 'https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                maximumLevel: 18,
                credit: '高德地图'
            });
            labelLayer = new Cesium.UrlTemplateImageryProvider({
                url: 'https://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
                maximumLevel: 18,
                credit: '高德地图标注'
            });
            viewer.imageryLayers.addImageryProvider(baseLayer);
            viewer.imageryLayers.addImageryProvider(labelLayer);
            break;

        case 'satelliteWithLabels':
            // 卫星影像 + 标注
            baseLayer = new Cesium.UrlTemplateImageryProvider({
                url: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                maximumLevel: 18,
                credit: '高德地图影像'
            });
            labelLayer = new Cesium.UrlTemplateImageryProvider({
                url: 'https://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
                maximumLevel: 18,
                credit: '高德地图标注'
            });
            viewer.imageryLayers.addImageryProvider(baseLayer);
            viewer.imageryLayers.addImageryProvider(labelLayer);
            break;
    }
}

export default async function initCesium() {
    window.CESIUM_BASE_URL = '/Cesium';
    Cesium.Ion.defaultAccessToken = Token;

    // 创建 Viewer 时禁用底部控件和其他不需要的部件
    const viewer = new Cesium.Viewer("cesiumContainer", {
        animation: false,                 // 隐藏动画控件
        timeline: false,                  // 隐藏时间线控件
        infoBox: true,                   // 隐藏信息框
        selectionIndicator: false,        // 隐藏选择指示器 
        terrain: Cesium.Terrain.fromWorldTerrain(), // 添加地形
        imageryProvider: false
    });

    // 初始化默认图层（矢量地图）

    viewer.camera.flyTo({
        destination: Cesium.Rectangle.fromDegrees(
            73.5,   // 西经(中国西部边界)
            18.0,   // 南纬(中国南部边界)
            135.5,  // 东经(中国东部边界)
            53.5    // 北纬(中国北部边界)
        )
    });

    const buildingTileset = await Cesium.createOsmBuildingsAsync();
    viewer.scene.primitives.add(buildingTileset);

    const entities = viewer.entities;
    // 存储所有城市实体的数组
    const cityEntities = [];
    // 存储所有国家实体的数组
    const countryEntities = [];

    // 循环创建城市实体
    cities.forEach(city => {
        const entity = entities.add({
            // 为点标设置一定高度，避免被地面或建筑物遮挡
            position: Cesium.Cartesian3.fromDegrees(city.longitude, city.latitude, 100), // 增加高度
            billboard: {
                image: '/pointImg/city_point.png',
                scale: 0.06,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, -9),
                disableDepthTestDistance: Number.POSITIVE_INFINITY // 禁用深度测试
            },
            label: {
                text: city.name,
                font: '14px sans-serif',
                fillColor: Cesium.Color.WHITE,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 2,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, -9),
                disableDepthTestDistance: Number.POSITIVE_INFINITY // 禁用深度测试  
            },
            description: city.description
        });
        cityEntities.push(entity);
    });
    console.log("🚀 ~ initCesium ~ cities:", cities)

    // 循环创建国家实体
    countries.forEach(country => {
        const entity = entities.add({
            // 为点标设置一定高度，避免被地面或建筑物遮挡
            position: Cesium.Cartesian3.fromDegrees(country.longitude, country.latitude, 100),
            billboard: {
                image: '/pointImg/country_point.png', // 使用不同的图标表示国家
                scale: 0.08, // 国家点标稍大一些
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, -9),
                disableDepthTestDistance: Number.POSITIVE_INFINITY // 禁用深度测试
            },
            label: {
                text: country.name,
                font: '16px sans-serif', // 国家标签字体稍大
                fillColor: Cesium.Color.YELLOW, // 使用不同颜色区分国家标签
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 2,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, -9),
                disableDepthTestDistance: Number.POSITIVE_INFINITY // 禁用深度测试  
            },
            description: country.description
        });
        countryEntities.push(entity);
    });
    console.log("🚀 ~ initCesium ~ countries:", countries)

    viewer.zoomTo(entities); // 缩放到所有实体

    // 添加点击事件监听
    viewer.screenSpaceEventHandler.setInputAction(function (click) {
        const pickedObject = viewer.scene.pick(click.position);
        if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id)) {
            const entity = pickedObject.id;
            if (entity.description) {
                dialogVisible.value = true;
                dialogContent.value = entity.description._value;
            }
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 在 initCesium 函数中移除或注释掉相机事件监听器中的显示控制逻辑
    // 监听相机移动事件，只计算距离但不控制显示
    viewer.camera.changed.addEventListener(() => {
        const cameraPosition = viewer.camera.position;

        // 为每个实体添加距离属性，但不直接控制显示
        cityEntities.forEach(entity => {
            if (entity.position) {
                const entityPosition = entity.position.getValue(Cesium.JulianDate.now());
                if (entityPosition) {
                    const distance = Cesium.Cartesian3.distance(cameraPosition, entityPosition);
                    // 将距离存储在实体的自定义属性中
                    entity._distance = distance;
                }
            }
        });

        countryEntities.forEach(entity => {
            if (entity.position) {
                const entityPosition = entity.position.getValue(Cesium.JulianDate.now());
                if (entityPosition) {
                    const distance = Cesium.Cartesian3.distance(cameraPosition, entityPosition);
                    // 将距离存储在实体的自定义属性中
                    entity._distance = distance;
                }
            }
        });
    });

    return {
        viewer,
        cityEntities,
        countryEntities
    };
}